package com.yuandian.management.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuandian.api.management.entity.ConfProbeManage;
import com.yuandian.api.management.entity.ConfProtocol;
import com.yuandian.api.management.validate.InsertFlag;
import com.yuandian.api.management.validate.UpdateFlag;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.management.service.ConfProbeManageService;
import com.yuandian.management.utils.JacksonUtil;
import com.yuandian.utils.IpUtils;
import com.yuandian.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 探针采集配置表-Controller
 * @author zfsn
 * @date 2023-4-17
 */
@Slf4j
@Api(tags = "探针管理-探针采集管理")
@RestController
@RequestMapping("/probeManage")
public class ConfProbeManageController {

	@Autowired
	private ConfProbeManageService confProbeManageService;

	// 是否正在进行同步操作
	public static boolean isWork=false;

	//完成同步操作的时间
	public static Date finishWorkDate;

	/**
	 * 查询探针配置列表
	 *
	 * @param reqDto
	 * @return
	 */
	@PostMapping("/pageInfo")
	@ApiOperation(value = "查询探针配置列表", notes = "查询探针配置列表")
	public R queryPageInfo(@RequestBody ConfProbeManage reqDto) {
		log.info("[探针采集配置管理][查询探针配置列表] {}", JacksonUtil.objectToString(reqDto));
		Page<ConfProbeManage> pageDataInfo = confProbeManageService.queryPageInfo(reqDto);
		return R.ok(pageDataInfo);
	}

	/**
	 * 查询探针状态
	 *
	 * @param idList
	 * @return
	 */
	@GetMapping("/listStatus")
	@ApiOperation(value = "查询探针状态", notes = "查询探针状态")
	public R queryStatusByIds(@RequestParam("idList") List<Integer> idList) {
		log.info("[探针采集配置管理][查询探针状态] {}", JacksonUtil.objectToString(idList));
		if (CollectionUtils.isEmpty(idList)) {
			return R.failed("id不能为空");
		}
		List<ConfProbeManage> respDtos = confProbeManageService.queryStatusForList(idList);
		return R.ok(respDtos);
	}

	/**
	 * 详情
	 *
	 * @param id
	 * @return
	 */
	@GetMapping("/detail/{id}")
	@ApiOperation(value = "详情", notes = "详情")
	public R probeDetail(@PathVariable("id") Integer id) {
		log.info("[探针采集配置管理][详情] {}", id);
		ConfProbeManage respDto = confProbeManageService.probeDetail(id);
		return R.ok(respDto);
	}

	/**
	 * 查询探针运行信息且更新运行信息
	 *
	 * @param id
	 * @return
	 */
	@GetMapping("/running/{id}")
	@ApiOperation(value = "查询探针运行详情", notes = "查询探针运行详情")
	public R queryProbeRunBeforeUpdate(@PathVariable("id") Integer id) {
		log.info("[探针采集配置管理][查询探针运行详情] {}", id);
		Objects.requireNonNull(id, "id不能为空");
		ConfProbeManage respDto = confProbeManageService.queryProbeRunning(id);
		return R.ok(respDto);
	}

	/**
	 * 新增探针采集配置
	 *
	 * @param reqDto
	 * @return
	 */
	@PostMapping("/save")
	@ApiOperation(value = "新增探针采集配置", notes = "新增探针采集配置")
	public R saveProbe(@RequestBody @Validated({InsertFlag.class}) ConfProbeManage reqDto) {
		log.info("[探针采集配置管理][新增探针采集配置] {}", JacksonUtil.objectToString(reqDto));
		if (StringUtils.isNotEmpty(reqDto.getIp()) &&
				(IpUtils.isValidIPAddress(reqDto.getIp()) || IpUtils.isIPv6(reqDto.getIp()))) {
			return confProbeManageService.saveProbe(reqDto);
		} else {
			return R.failed("IP格式不正确");
		}
	}

	/**
	 * 编辑探针采集配置
	 *
	 * @param reqDto
	 * @return
	 */
	@PostMapping("/updateDetail")
	@ApiOperation(value = "编辑探针采集配置", notes = "编辑探针采集配置")
	public R updateProbeDetail(@RequestBody ConfProbeManage reqDto) {
		log.info("[探针采集配置管理][编辑探针采集配置] {}", JacksonUtil.objectToString(reqDto));
		Objects.requireNonNull(reqDto.getId(), "id不能为空");

		if (StringUtils.isNotEmpty(reqDto.getIp()) &&
				(IpUtils.isValidIPAddress(reqDto.getIp()) || IpUtils.isIPv6(reqDto.getIp()))) {
			return confProbeManageService.updateProbeDetail(reqDto);

		} else {
			return R.failed("IP格式不正确");
		}
	}

	/**
	 * 查询探针协议配置列表
	 *
	 * @param reqDto
	 * @return
	 */
	@PostMapping("/protocolPage")
	@ApiOperation(value = "查询探针协议配置列表", notes = "查询探针协议配置列表")
	public R queryProbeProtocol(@RequestBody ConfProbeManage reqDto) {
		log.info("[探针采集配置管理][查询探针协议配置列表] {}", JacksonUtil.objectToString(reqDto));
		Page<ConfProtocol> pageDataInfo = confProbeManageService.queryProbeProtocol(reqDto);
		return R.ok(pageDataInfo);
	}

	/**
	 * 批量删除配置
	 *
	 * @param ids
	 * @return
	 */
	@DeleteMapping("/delProbe/{ids}")
	@ApiOperation(value = "批量删除配置", notes = "批量删除配置")
	public R delProbe(@PathVariable("ids") List<Integer> ids) {
		log.info("[探针采集配置管理][批量删除配置] {}", JacksonUtil.objectToString(ids));
		return confProbeManageService.delProbe(ids);
	}

	/**
	 * 更新探针状态
	 *
	 * @param reqDto
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/updateStatus")
	@ApiOperation(value = "更新探针状态", notes = "更新探针状态")
	public R updateProbeStatus(@RequestBody ConfProbeManage reqDto) throws Exception {
		if(ObjectUtil.isEmpty(reqDto.getId())){
			return R.failed("探针ID不能为空！");
		}
		if(ObjectUtil.isEmpty(reqDto.getIsStatus())){
			return R.failed("探针状态不能为空！");
		}
		log.info("[探针采集配置管理][更新探针状态] id:{} status：{}", reqDto.getId(), reqDto.getIsStatus());
		return confProbeManageService.updateProbeStatus(reqDto);
	}

	/**
	 * 同步业务配置
	 *
	 * @param reqDto
	 * @return
	 */
	@PostMapping("/syncBusiness")
	@ApiOperation(value = "同步业务配置", notes = "同步业务配置")
	public R syncBusiness(@RequestBody ConfProbeManage reqDto) {
		log.info("[探针采集配置管理][同步业务配置] reqDto{}", JacksonUtil.objectToString(reqDto));
		//判断是否有正在进行的同步操作，如果有，则直接返回错误信息
		if (isWork){
			return R.failed(1001,"上次请求正在执行同步，本次请求无效");
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				//进行同步操作时，将isWork标志设为true，标识正在同步，不允许下一个同步请求执行，待操作完成改成false
				isWork=true;
				confProbeManageService.syncBusiness(reqDto);
				isWork=false;
				finishWorkDate=new Date();
			}
		}).start();
		return R.ok();
	}

	/**
	 * 同步ip过滤配置
	 *
	 * @param reqDto
	 * @return
	 */
	@PostMapping("/syncIp")
	@ApiOperation(value = "同步ip过滤配置", notes = "同步ip过滤配置")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "ip", value = "ip", paramType = "body", required = true, dataType = "String", dataTypeClass = String.class)
	})
	public R syncIp(@RequestBody @ApiIgnore ConfProbeManage reqDto) {
		log.info("[探针采集配置管理][同步ip过滤配置] reqDto{}", JacksonUtil.objectToString(reqDto));
		return confProbeManageService.syncIp(reqDto);
	}

	/**
	 * 同步协议
	 *
	 * @param ip
	 * @return
	 */
	@GetMapping("/syncProtocol/{ip}")
	@ApiOperation(value = "同步协议", notes = "同步协议")
	public R<String> syncProtocolByIp(@PathVariable("ip") String ip) {
		log.info("[探针采集配置管理][同步协议] ip{}", ip);
		return confProbeManageService.syncProtocolByIp(ip);
	}


	/**
	 * 清空Ip过滤配置
	 *
	 * @param reqDto
	 * @return
	 */
	@PostMapping("/cleanIp")
	@ApiOperation(value = "清空Ip过滤配置", notes = "清空Ip过滤配置")
	public R cleanIp(@RequestBody ConfProbeManage reqDto) {
		log.info("[探针采集配置管理][清空Ip过滤配置] reqDto {}", JacksonUtil.objectToString(reqDto));
		return confProbeManageService.cleanIp(reqDto);
	}


}
